{% extends 'base.attached.class' %}

{% block content %}
{% if is_test or to_json %}
require 'json'


{% endif %}
class {{ class_name }}

	def initialize (lefts, rights, thresholds, indices, classes)
		@lefts = lefts
		@rights = rights
		@thresholds = thresholds
		@indices = indices
		@classes = classes
	end

	def _find_max (nums)
		idx = 0
		for i in 0 ... nums.length
			idx = nums[i] > nums[idx] ? i : idx
		end
		idx
	end

	def _norm_vals (nums)
		result = []
		sum = 0
		for i in 0 ... nums.length
			sum += nums[i]
		end
		if sum == 0
			l = nums.length
			for i in 0 ... l
				result[i] = 1.0 / l
			end
		else
			for i in 0 ... nums.length
				result[i] = nums[i] / sum
			end
		end
		result
	end

	def _compute (features, node, post)
		if @thresholds[node] != -2
			if features[@indices[node]] <= @thresholds[node]
				return _compute features, @lefts[node], post
			else
				return _compute features, @rights[node], post
			end
		end
		post.call @classes[node]
	end

	def predict (features)
		_compute features, 0, post=method(:_find_max)
	end

	def predict_proba (features)
		_compute features, 0, post=method(:_norm_vals)
	end

end

if __FILE__ == $0
	if ARGV.length != {{ n_features }}
		raise "You have to pass {{ n_features }} features."
	end

	# Features:
	features = ARGV.collect(&:to_f)

	# Model data:
	{{ lefts }}
	{{ rights }}
	{{ thresholds }}
	{{ indices }}
	{{ classes }}

	# Estimator:
	clf = {{ class_name }}.new lefts, rights, thresholds, indices, classes

	{% if is_test or to_json %}
	# Get JSON:
	prediction = clf.predict features
	probabilities = clf.predict_proba features
	puts JSON.generate({:predict => prediction, :predict_proba => probabilities})
	{% else %}
	# Get class prediction:
	prediction = clf.predict features
	puts "Predicted class: ##{prediction}"

	# Get class probabilities:
	probabilities = clf.predict_proba features
	for i in 0 ... probabilities.length
		puts "Probability of class ##{i} : #{probabilities[i]}"
	end
	{% endif %}
end
{% endblock %}